package com.zyh.controller;

import com.zyh.entity.Comment;
import com.zyh.entity.School;
import com.zyh.entity.ShowDto;
import com.zyh.service.CommentService;
import com.zyh.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/school")
public class SchoolController {
    @Autowired
    SchoolService service;
    @Autowired
    CommentService commentService;
    @Resource
    RedisTemplate<String,Object> template;

    @GetMapping("/{id}")
    public ShowDto selectById(@PathVariable("id") int id){
        ValueOperations<String, Object> stringObjectValueOperations = template.opsForValue();
        Long views = stringObjectValueOperations.increment(id + ":views");
        Object o = stringObjectValueOperations.get(id + ":favorite");
        School school = service.selectById(id);
        if(o!=null){
            Integer l = (Integer)o;
            school.setFavorite(l);
        }
        school.setViews(views);

        List<Comment> comments = commentService.selectBySchoolId(id);
        ShowDto dto = new ShowDto(school,comments);
        return dto;
    }
    @PutMapping("/{id}")
    public void incrFavorite(@PathVariable("id") int id){
        ValueOperations<String, Object> stringObjectValueOperations = template.opsForValue();
        stringObjectValueOperations.increment(id + ":favorite");
        stringObjectValueOperations.decrement(id + ":views");
    }

    @GetMapping("/")
    public List<School> selectAll(){
        return service.selectAll();
    }
}
